package com.magupe.im.web.db.service.h2;

import java.sql.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class H2DataPool {

    private static final String JDBC_URL_M = "jdbc:h2:mem:DBName;DB_CLOSE_DELAY=-1";
    private static final String JDBC_URL_A = "jdbc:h2:file:~/h2db";
    private static final String JDBC_URL_R = "jdbc:h2:file:./h2db/message";

    private static final String USER = "root";
    private static final String PASSWORD = "880204";
    private static final String DRIVER_CLASS = "org.h2.Driver";

    private BlockingQueue<Connection> pool = new ArrayBlockingQueue<Connection>(100);

    private int count = 10;

    static {
        try {
            Class.forName(DRIVER_CLASS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public H2DataPool(){
        addConnection(this.count);
    }

    public H2DataPool(int count) {
        addConnection(count);
    }

    private void addConnection(int count){
        for(int i = 1; i <= count; i++) {
            try {
                pool.put(getOriginConnection());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private Connection getOriginConnection(){
        try{
            return DriverManager.getConnection(JDBC_URL_R, USER, PASSWORD);
        }catch(SQLException e){
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    public Connection getConnection() throws SQLException {
        try {
            final Connection conn = pool.take();
            return conn;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void releaseConnection(Connection conn) {
        try {
            pool.put(conn);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public void releaseRs(ResultSet rs){
        if(rs != null){
            try{
                rs.close();
                rs = null;
            }catch(SQLException e){
                e.printStackTrace();
                throw new RuntimeException();
            }
        }
    }

    public void releaseStmt(Statement stmt){
        if(stmt != null){
            try{
                stmt.close();
                stmt = null;
            }catch(SQLException e){
                e.printStackTrace();
                throw new RuntimeException();
            }
        }
    }
}
